const express = require('express');
const router = express.Router();
const axios = require('axios');

// Ollama API配置
const API_URL = 'http://127.0.0.1:11434/api/chat';

// 代理Ollama API请求
router.post('/chat', async (req, res) => {
  // 设置SSE headers
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  try {
    // 确保消息是字符串
    const messageContent = Array.isArray(req.body.messages) ? req.body.messages.join('\n') : req.body.messages;

    const response = await axios.post(API_URL, {
      model: "deepseek-r1:7b",
      messages: [
        {
          role: "user",
          content: messageContent
        }
      ],
      stream: true
    }, {
      responseType: 'stream'
    });

    // 处理流式响应
    response.data.on('data', chunk => {
      try {
        const lines = chunk.toString().split('\n').filter(line => line.trim());
        for (const line of lines) {
          const data = JSON.parse(line);
          if (data.message?.content) {
            // 发送消息内容
            res.write(`data: ${JSON.stringify({ content: data.message.content })}\n\n`);
          }
        }
      } catch (error) {
        console.error('处理流数据错误:', error);
      }
    });

    response.data.on('end', () => {
      res.write('data: [DONE]\n\n');
      res.end();
    });

    // 处理客户端断开连接
    req.on('close', () => {
      res.end();
    });

  } catch (error) {
    console.error('AI服务请求失败:', error.response?.data || error.message);
    res.write(`data: ${JSON.stringify({ error: '调用AI服务失败' })}\n\n`);
    res.end();
  }
});

module.exports = router; 